package com.tpnexus;

import java.util.List;
import org.hibernate.Session;
import org.junit.Test;

public class ProductManager {

	@Test
	public void testSetProduct() throws Exception {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		Product product = new Product();
		product.setManufacture("test manufacture");
		product.setProductDesc("Hibernate test");
		product.setProductName("Hibernate");
		product.setProductPrice(10);
		session.save(product);
		session.getTransaction().commit();
		HibernateUtil.getSessionFactory().close();

	}

	@Test
	public void testDeleteProduct() throws Exception {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			Product product = (Product) session.get(Product.class, 5);
			session.delete(product);
			session.getTransaction().commit();
		} catch (RuntimeException e) {
			session.getTransaction().rollback();
			throw e;
		} finally {
			HibernateUtil.getSessionFactory().close();
		}

	}

	@Test
	public void testUpdateProduct() throws Exception {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			Product product = (Product) session.get(Product.class, 5);
			System.out.println("before update:" + product);
			product.setProductName("test update");
			session.update(product);
			System.out.println("after update:" + product);
			session.getTransaction().commit();
		} catch (RuntimeException e) {
			session.getTransaction().rollback();
			throw e;
		} finally {
			HibernateUtil.getSessionFactory().close();
		}

	}

	@Test
	public void testGetProduct() throws Exception {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		List<Product> list = session.createQuery(" from Product").list();
		for (Product product : list) {
			System.out.println(product);
		}
		session.getTransaction().commit();
		HibernateUtil.getSessionFactory().close();
	}

}
